package com.jumi.microservice.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.constant.compensation.AfterSaleEnum;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.constant.compensation.CheckStatusEnum;
import com.jumi.microservice.constant.compensation.LockFlagEnum;
import com.jumi.microservice.constant.refundgoods.CancelUserFlagEnum;
import com.jumi.microservice.constant.refundgoods.ReceivedStatusEnum;
import com.jumi.microservice.constant.reissue.*;
import com.jumi.microservice.dto.order.OrderLogRequest;
import com.jumi.microservice.dto.reissue.ReissueCheckRequest;
import com.jumi.microservice.dto.serviceDto.OrderGoodsServiceDetailsRequest;
import com.jumi.microservice.dto.serviceDto.OrderGoodsServiceDetailsResponse;
import com.jumi.microservice.dto.serviceDto.UpdateAfterSealStatusRequest;
import com.jumi.microservice.dto.serviceDto.UpdateReturnInfoRequest;
import com.jumi.microservice.entity.AfterSealOrder;
import com.jumi.microservice.entity.AfterSealOrderGoods;
import com.jumi.microservice.entity.Compensation;
import com.jumi.microservice.entity.Reissue;
import com.jumi.microservice.mapper.AfterSealOrderGoodsMapper;
import com.jumi.microservice.mapper.AfterSealOrderMapper;
import com.jumi.microservice.mapper.CompensationMapper;
import com.jumi.microservice.mapper.ReissueMapper;
import com.jumi.microservice.service.IOrderDubboService;
import com.jumi.microservice.service.IOrderService;
import com.jumi.microservice.service.IReissueService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author scw
 * @date 2020/9/28
 */
@DubboService(interfaceClass = IReissueService.class)
public class AdminReissueServiceImpl implements IReissueService {
    @Resource
    private ReissueMapper reissueMapper;
    @Resource
    private AfterSealOrderMapper afterSealOrderMapper;
    @Resource
    private AfterSealOrderGoodsMapper afterSealOrderGoodsMapper;
    @DubboReference
    private IOrderDubboService iOrderDubboService;
    @DubboReference
    private IOrderService iOrderService;
    @Resource
    private CompensationMapper compensationMapper;

    /**
     * 补发审核
     *
     * @param reissueCheckRequest
     * @return
     */
    @Override
    @org.springframework.transaction.annotation.Transactional
    public Boolean checkReissue(ReissueCheckRequest reissueCheckRequest) {
        Long operatorId = reissueCheckRequest.getOperatorId();
        String operatorName = reissueCheckRequest.getOperatorName();
        boolean postageFlag = false;
        boolean res = false;
        //查询信息
        QueryWrapper<Reissue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reissue_order_no", reissueCheckRequest.getReissueOrderNo());
        queryWrapper.eq("status", ReissueStatusEnum.STATUS_WAIT.getCode());
        queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_YES.getCode());
        Reissue reissue = reissueMapper.selectOne(queryWrapper);
        String generateOrderSnSh = "";
        if (reissue != null) {
            //审核状态更新
            reissue.setStatus(reissueCheckRequest.getStatus());
            reissue.setCheckRemark(reissueCheckRequest.getCheckRemark());
            reissue.setCheckTime(new Date());
            reissue.setCheckOperatorId(operatorId);
            reissue.setCheckOperatorName(operatorName);
            //换货
            if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_REPLACE.getCode().byteValue()) {
                /*
                 * 补偿邮费
                 * 默认锁定执行解锁操作
                 * 是否锁定: 0-否 1-是
                 */
                QueryWrapper<Compensation> queryWrapperCompensation = new QueryWrapper<>();
                queryWrapperCompensation.eq("refund_id", reissue.getId());
                queryWrapperCompensation.eq("lock_flag", LockFlagEnum.LOCK_FLAG_YES.getCode());
                queryWrapperCompensation.eq("after_sale_type", AfterSaleEnum.AFTER_SALE_BCYF.getCode());
                queryWrapperCompensation.eq("postage_type", PostageTypeEnum.POSTAGE_TYPE_REISSUE.getCode());
                queryWrapperCompensation.eq("check_status", CheckStatusEnum.CHECK_STATUS_WAIT.getCode());
                queryWrapperCompensation.eq("original_order_id", reissue.getOriginalOrderId());
                queryWrapperCompensation.eq("compensation_goods_id", reissue.getGoodsId());
                queryWrapperCompensation.eq("buyer_id", reissue.getBuyerId());
                queryWrapperCompensation.orderByDesc("id");
                queryWrapperCompensation.last("limit 1");
                Compensation compensation = compensationMapper.selectOne(queryWrapperCompensation);
                if (compensation != null) {
                    //同意
                    if (reissueCheckRequest.getStatus() == ReissueCheckStatusEnum.CHECK_STATUS_PASSED.getCode().byteValue()) {
                        compensation.setLockFlag(LockFlagEnum.LOCK_FLAG_NO.getCode().byteValue());
                        postageFlag = true;
                    } else if (reissueCheckRequest.getStatus() == ReissueCheckStatusEnum.CHECK_STATUS_FAILED.getCode().byteValue()) {
                        compensation.setCheckStatus(CheckStatusEnum.CHECK_STATUS_REFUSE.getCode().byteValue());
                        compensation.setCheckTime(new Date());
                        compensation.setCheckOperatorId(operatorId);
                        compensation.setCheckOperatorName(operatorName);
                        compensation.setCheckRemark("换货处理被拒");
                    }
                    compensationMapper.updateById(compensation);
                }
            }
            //审核通过创建订单
            if (reissueCheckRequest.getStatus() == ReissueCheckStatusEnum.CHECK_STATUS_PASSED.getCode().byteValue()) {
                //仓库ID
                if (reissueCheckRequest.getWareHouseId() > 0) {
                    reissue.setSupplierId(reissueCheckRequest.getWareHouseId());
                }
                //根据订单ID和商品ID查询原支付订单信息
                OrderGoodsServiceDetailsRequest orderGoodsServiceDetailsRequest = new OrderGoodsServiceDetailsRequest();
                orderGoodsServiceDetailsRequest.setOrderId(reissue.getOriginalOrderId());
                orderGoodsServiceDetailsRequest.setGoodsId(reissue.getGoodsId());
                OrderGoodsServiceDetailsResponse orderGoodsServiceDetailsResponse = iOrderService.findOrderGoodsDetails(orderGoodsServiceDetailsRequest);
                if (orderGoodsServiceDetailsResponse != null) {
                    //创建售后订单
                    AfterSealOrder afterSealOrder = new AfterSealOrder();
                    //补发/补发漏发/换货ID
                    afterSealOrder.setReissueId(reissue.getId());
                    //补发/补发漏发/换货名称
                    afterSealOrder.setReissueNo(reissue.getReissueOrderNo());
                    //补发/补发漏发/换货备注
                    afterSealOrder.setReissueRemark(reissue.getRemark());
                    //补发原因: 0-做单/登记失误 1-仓储发货原因 2-快递原因 3-产品原因 4-顾客自身原因
                    afterSealOrder.setReissueReason(reissue.getReissueReason());
                    //发起人姓名
                    afterSealOrder.setPromoterName(reissue.getPromoterName());
                    //原订单ID
                    afterSealOrder.setOriginalOrderId(orderGoodsServiceDetailsResponse.getId());
                    //原订单编号
                    afterSealOrder.setOriginalOrderNo(orderGoodsServiceDetailsResponse.getOrderNo());
                    //售后订单编号
                    generateOrderSnSh = this.generateOrderSnSh();
                    afterSealOrder.setOrderNo(generateOrderSnSh);
                    afterSealOrder.setBuyerId(orderGoodsServiceDetailsResponse.getBuyerId());
                    afterSealOrder.setBuyerRole(orderGoodsServiceDetailsResponse.getBuyerRole());
                    //订单团购价 = 商品团购价 * 商品数量
                    BigDecimal orderPromotionAmount = orderGoodsServiceDetailsResponse.getGoodsPromotionPrice().multiply(BigDecimal.valueOf(orderGoodsServiceDetailsResponse.getGoodsAmount()));
                    afterSealOrder.setOrderPromotionAmount(orderPromotionAmount);
                    //用户级别：1、团购用户 2、店长 3、优秀店长 4、金牌推广商
                    if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_PROMOTION.getCode().byteValue()) {
                        afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsPromotionPrice());
                    } else if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_PLATINUM.getCode().byteValue()) {
                        afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsPlatinumPrice());
                    } else if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_DIAMONDS.getCode().byteValue()) {
                        afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsDiamondsPrice());
                    } else if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_KING.getCode().byteValue()) {
                        afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsKingPrice());
                    }
                    afterSealOrder.setOrderType(reissue.getReissueType());
                    String receiverName = reissue.getReceiverName();
                    if (receiverName == null || "".equals(receiverName) || receiverName.length() == 0) {
                        receiverName = orderGoodsServiceDetailsResponse.getReceiverName();
                    }
                    afterSealOrder.setReceiverName(receiverName);
                    String receiverPhone = reissue.getReceiverPhone();
                    if (receiverPhone == null || "".equals(receiverPhone) || receiverPhone.length() == 0) {
                        receiverPhone = orderGoodsServiceDetailsResponse.getReceiverPhone();
                    }
                    afterSealOrder.setReceiverPhone(receiverPhone);
                    String receiverAddress = reissue.getReceiverAddress();
                    if (receiverAddress == null || "".equals(receiverAddress) || receiverAddress.length() == 0) {
                        receiverAddress = orderGoodsServiceDetailsResponse.getReceiverAddress();
                    }
                    afterSealOrder.setReceiverAddress(receiverAddress);
                    //海外商品
                    if (orderGoodsServiceDetailsResponse.getIsImport() == ImportFlagEnum.IMPORT_FLAG_YES.getCode().byteValue()) {
                        //收件人真实姓名
                        afterSealOrder.setReceiverRealName(orderGoodsServiceDetailsResponse.getReceiverRealName());
                        //收货人证件号
                        afterSealOrder.setReceiverCardNo(orderGoodsServiceDetailsResponse.getReceiverCardNo());
                    }
                    if (afterSealOrderMapper.insert(afterSealOrder) > 0) {
                        //获取添加主键ID
                        int orderId = afterSealOrder.getId();
                        //创建售后订单商品
                        AfterSealOrderGoods afterSealOrderGoods = new AfterSealOrderGoods();
                        afterSealOrderGoods.setOrderId(orderId);
                        afterSealOrderGoods.setGoodsId(orderGoodsServiceDetailsResponse.getGoodsId());
                        afterSealOrderGoods.setGoodsName(orderGoodsServiceDetailsResponse.getGoodsName());
                        afterSealOrderGoods.setGoodsAmount(reissue.getGoodsNum());
                        afterSealOrderGoods.setGoodsPromotionPrice(orderGoodsServiceDetailsResponse.getGoodsPromotionPrice());
                        afterSealOrderGoods.setGoodsPlatinumPrice(orderGoodsServiceDetailsResponse.getGoodsPlatinumPrice());
                        afterSealOrderGoods.setGoodsDiamondsPrice(orderGoodsServiceDetailsResponse.getGoodsDiamondsPrice());
                        afterSealOrderGoods.setGoodsKingPrice(orderGoodsServiceDetailsResponse.getGoodsKingPrice());
                        afterSealOrderGoods.setGoodsPrice(orderGoodsServiceDetailsResponse.getGoodsPrice());
                        afterSealOrderGoods.setGoodsCostPrice(orderGoodsServiceDetailsResponse.getGoodsCostPrice());
                        afterSealOrderGoods.setGoodsCoverImg(orderGoodsServiceDetailsResponse.getGoodsCoverImg());
                        afterSealOrderGoods.setSelfFlag(orderGoodsServiceDetailsResponse.getSelfFlag());
                        afterSealOrderGoods.setSupplierId(orderGoodsServiceDetailsResponse.getSupplierId());
                        afterSealOrderGoods.setGoodsWeight(orderGoodsServiceDetailsResponse.getGoodsWeight());
                        //仓库ID
                        if (reissueCheckRequest.getWareHouseId() > 0) {
                            afterSealOrderGoods.setWarehouse(reissueCheckRequest.getWareHouseId());
                        } else {
                            afterSealOrderGoods.setWarehouse(orderGoodsServiceDetailsResponse.getRealWarehouse());
                        }
                        afterSealOrderGoods.setWarehouseSn(orderGoodsServiceDetailsResponse.getWarehouseSn());
                        afterSealOrderGoods.setIsImport(orderGoodsServiceDetailsResponse.getIsImport());
                        afterSealOrderGoodsMapper.insert(afterSealOrderGoods);
                    }
                }
            }
            if (reissueMapper.updateById(reissue) > 0) {
                /*
                 * 订单商品表更新售后状态
                 * 售后状态:
                 *      0-正常 1-已退款
                 *      2-退货审核中 3-已退货退款 4-退货退款拒绝
                 *      5-补发审核中 6-已补发 7-补发拒绝
                 *      8-补偿审核中 9-已补偿 10-补偿拒绝
                 *      11-补邮审核中 12-已补邮费 13-补邮拒绝
                 *      14-换货申请中 15-换货同意  16-换货拒绝
                 *      17-补发漏发审核中 18-已补发漏发 19-补发漏发拒绝
                 *      补发：after_seal_status = 6 、after_seal_status = 7
                 *      补发漏发：after_seal_status = 18 、after_seal_status = 19
                 *      换货：after_seal_status = 15 、after_seal_status = 16
                 */
                //int afterSealStatus = reissueCheckRequest.getStatus() == 1 ? 6 : 7;
                int afterSealStatus = 0;
                if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
                    afterSealStatus = reissueCheckRequest.getStatus() == ReissueStatusEnum.STATUS_PASSED.getCode().byteValue() ? AfterSaleStatusEnum.REISSUE_AGREE.getCode() : AfterSaleStatusEnum.REISSUE_REFUSE.getCode();
                } else if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
                    afterSealStatus = reissueCheckRequest.getStatus() == ReissueStatusEnum.STATUS_PASSED.getCode().byteValue() ? AfterSaleStatusEnum.REISSUE_MISSED_AGREE.getCode() : AfterSaleStatusEnum.REISSUE_MISSED_REFUSE.getCode();
                } else {
                    afterSealStatus = reissueCheckRequest.getStatus() == ReissueStatusEnum.STATUS_PASSED.getCode().byteValue() ? AfterSaleStatusEnum.REPLACE_AGREE.getCode() : AfterSaleStatusEnum.REPLACE_REFUSE.getCode();
                }
                //自营商品审核通过，更新数量
                if (afterSealStatus == AfterSaleStatusEnum.REISSUE_AGREE.getCode() || afterSealStatus == AfterSaleStatusEnum.REISSUE_MISSED_AGREE.getCode() || afterSealStatus == AfterSaleStatusEnum.REPLACE_AGREE.getCode()) {
                    UpdateReturnInfoRequest updateReturnInfoRequest = new UpdateReturnInfoRequest();
                    updateReturnInfoRequest.setOrderId(reissue.getOriginalOrderId());
                    updateReturnInfoRequest.setGoodsId(reissue.getGoodsId());
                    updateReturnInfoRequest.setReturnCount(reissue.getGoodsNum());
                    updateReturnInfoRequest.setReturnPrice(BigDecimal.valueOf(0));
                    updateReturnInfoRequest.setReturnPostage(BigDecimal.valueOf(0));
                    iOrderService.updateReturnInfo(updateReturnInfoRequest);
                }
                if (postageFlag) {
                    if (reissueCheckRequest.getStatus() == ReissueStatusEnum.STATUS_PASSED.getCode().byteValue()) {
                        afterSealStatus = AfterSaleStatusEnum.COMPENSATION_POSTAGE_APPLY.getCode();
                    }
                }
                UpdateAfterSealStatusRequest updateAfterSealStatusRequest = new UpdateAfterSealStatusRequest();
                updateAfterSealStatusRequest.setOrderId(reissue.getOriginalOrderId());
                updateAfterSealStatusRequest.setGoodsId(reissue.getGoodsId());
                updateAfterSealStatusRequest.setAfterSealStatus((byte) afterSealStatus);
                iOrderService.updateAfterSealStatus(updateAfterSealStatusRequest);
                /*
                 * 操作日志表插入相关信息
                 */
                String logInfo = "售后处理-";
                if (reissueCheckRequest.getStatus() == ReissueCheckStatusEnum.CHECK_STATUS_PASSED.getCode().byteValue()) {
                    logInfo += "同意";
                } else {
                    logInfo += "拒绝";
                }
                if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
                    logInfo += "补发";
                } else if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
                    logInfo += "补发-漏发";
                } else {
                    logInfo += "换货";
                }
                if (reissueCheckRequest.getStatus() == ReissueCheckStatusEnum.CHECK_STATUS_PASSED.getCode().byteValue()) {
                    logInfo += "；售后订单编号：" + generateOrderSnSh;
                }
                //用户标识，1 前端用户， 2 后端管理员
                Byte userFlag = CancelUserFlagEnum.USER_FLAG_ADMIN.getCode().byteValue();
                OrderLogRequest orderLogRequest = new OrderLogRequest();
                orderLogRequest.setLog(logInfo);
                orderLogRequest.setOperatorId(operatorId);
                orderLogRequest.setOperatorName(operatorName);
                orderLogRequest.setUserFlag(userFlag);
                orderLogRequest.setOrderSn(reissue.getOriginalOrderNo());
                Boolean isAddLog = iOrderDubboService.addOrderLog(orderLogRequest);
                if (isAddLog) {
                    res = true;
                }
            }
        }
        return res;
    }

    /**
     * 生成订单号 售后
     */
    private String generateOrderSnSh() {
        String time = DateUtil.getAllMSTime().substring(2);
        int randomInt = ThreadLocalRandom.current().nextInt(10, 100);
        return "SH" + time + randomInt;
    }
}
